<?php
/**
 * @purpose 商品逻辑处理
 * User: peter
 * Date: 2018/6/4
 * Time: 下午4:35
 */

namespace app\admin\logic;


use app\model\GoodsAttach;
use app\model\GoodsAttribute;
use app\model\GoodsAttributeAttach;
use extend\Functions;
use extend\STATUS_CODE;

class Goods extends Base
{
    /**
     * @purpose 发布商品
     * @param array $data
     * @return array
     */
    public static function create (array $data): array
    {
        if (!isset($data['title']) || empty($data['title'])) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少商品标题!'
            );
        }
        if (!isset($data['thumb']) || empty($data['thumb'])) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少商品封面图!'
            );
        }
        if (!isset($data['images']) || empty($data['images'])) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少商品展示图!'
            );
        }
        if (!isset($data['category']) || empty($data['category'])) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少分类信息!'
            );
        }
        if (!isset($data['brand']) || empty($data['brand'])) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少品牌信息!'
            );
        }
        if (!isset($data['article']) || empty($data['article'])) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少商品图文详情!'
            );
        }
        $goods                          = new \app\model\Goods();
        $attach                         = new GoodsAttach();
        $attribute                      = new GoodsAttribute();
        $attribute_attach               = new GoodsAttributeAttach();
        $category                       = new \app\model\Category();
        $brand                          = new \app\model\Brand();
        // 组装主表数据
        $goods_data                     = [];
        $goods_data['title']            = $data['title'];
        if ($data['thumb']) {
            $goods_data['thumb']        = $data['thumb'];
        } else {
            $goods_data['thumb']        = $data['images'][0];
        }
        $goods_data['category']      = $data['category'];
        $goods_data['category_name']    = $category->idToName($data['category']);
        $goods_data['brand']         = $data['brand'];
        $goods_data['brand_name']       = $brand->idToName($data['brand']);
        $goods_data['status']           = 2;
        $goods_data['price']            = (int) ($data['price']) * 100;
        $goods_data['stock']            = $data['stock'];
        $goods_data['images']           = $data['images'];
        $goods_data['pinyin']           = Functions::pinyin($data['title']);
        // 开启事物
        $goods->startTrans();
        $goods_result   = (bool) $goods->data($goods_data)->save();
        $goods_id       = $goods->id;
        // 组装附表数据
        $attach_data                = [];
        $attach_data['goods_id']    = $goods_id;
        $attach_data['article']     = $data['article'];
        $attach_data['parameter']   = $data['parameter'];
        $attach_result              = (bool) $attach->data($attach_data)->save();
        // 组装属性表
        $attribute_data             = [];
        foreach ($data['attribute'] as $item) {
            array_push($attribute_data, [
                'goods_id'          => $goods_id,
                'id'      => $item['id'],
                'name'    => $item['name'],
                'attach'  => $item['attach']
            ]);
        }
        // TODO saveAll方法新增数据返回的是包含新增模型（带自增ID）的数据集对象  因此这个地方的bool值需要通过其他方式获取
        $attribute_result = true;
        if (count($attribute_data) > 0) {
            $attribute_result =
                (bool) $attribute
                    ->saveAll($attribute_data);
        }
        $attribute_attach_data = [];
        foreach ($data['attribute_attach'] as $item) {
            $_data                              = [];
            $_data['goods_id']  = $goods_id;
            $_data['price']     = (int) ($item['price'] * 100);
            $_data['stock']     = $item['stock'];
            $_data['thumb']     = $item['thumb'];
            $_data['attach'] = $item['attach'];
            // 计算商品编号
            $number = $goods_id;
            foreach ($item['attach'] as $_attach) {
                $number .= $_attach['id'];
            }
            $number = Functions::str_sort($number);
            $_data['thumb']     = $item['thumb'];
            $_data['number']    = $number;
            array_push($attribute_attach_data, $_data);
        }
        // TODO saveAll方法新增数据返回的是包含新增模型（带自增ID）的数据集对象  因此这个地方的bool值需要通过其他方式获取
        $attribute_attach_result = true;
        if (count($attribute_attach_data) > 0) {
            $attribute_attach_result =
                (bool) $attribute_attach
                    ->saveAll($attribute_attach_data);
        }
        if ($goods_result &&
            $attach_result &&
            $attribute_result &&
            $attribute_attach_result) {
            $goods->commit();
            return Functions::result(STATUS_CODE::SUCCESS, '保存成功');
        }
        $goods->rollback();
        return Functions::result(STATUS_CODE::CREATE_FAIL, '保存失败!');
    }

    /**
     * @purpose 获取商品列表
     * @param array $where
     * @param int $page
     * @param int $size
     * @param string $order
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function items(
        $where = [],
        $page = 1,
        $size = 50,
        $order = 'create_at desc'): array
    {
        $model = new \app\model\Goods();
        $result = $model->items($where,$page,$size,$order);
        return Functions::result(
            STATUS_CODE::SUCCESS,
            $result
        );
    }

    /**
     * @purpose 通过ID获取单条数据
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function infoById (int $id): array
    {
        $model  = new \app\model\Goods();
        $fields = 'id,title,thumb,images,pinyin,price,stock,status,category,category_name,brand,brand_name';
        $result = $model
//            ->with('attach,goods_attribute,goods_attribute_attach')
//            ->with('attach,goods_attribute')
            ->with('attribute,attributeAttach,attach')
//            ->goodsAttribute()
            ->where('id', $id)
            ->field($fields)
            ->find();
        return Functions::result(
            STATUS_CODE::SUCCESS,
            $result
        );
    }

    /**
     * @purpose 编辑商品
     * @param array $data
     * @return array
     * @throws \think\exception\PDOException
     */
    public static function edit (array $data): array
    {
        if (!isset($data['id']) || empty($data['id'])) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少商品ID!'
            );
        }
        if (!isset($data['title']) || empty($data['title'])) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少商品标题!'
            );
        }
        if (!isset($data['thumb']) || empty($data['thumb'])) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少商品封面图!'
            );
        }
        if (!isset($data['images']) || empty($data['images'])) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少商品展示图!'
            );
        }
        if (!isset($data['category']) || empty($data['category'])) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少分类信息!'
            );
        }
        if (!isset($data['brand']) || empty($data['brand'])) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少品牌信息!'
            );
        }
        if (!isset($data['article']) || empty($data['article'])) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '缺少商品图文详情!'
            );
        }
        $goods_id                       = (int) $data['id'];
        $goods                          = new \app\model\Goods();
        $attach                         = new GoodsAttach();
        $attribute                      = new GoodsAttribute();
        $attribute_attach               = new GoodsAttributeAttach();
        $category                       = new \app\model\Category();
        $brand                          = new \app\model\Brand();
        // 组装主表数据
        $goods_data                     = [];
        $goods_data['title']            = $data['title'];
        if ($data['thumb']) {
            $goods_data['thumb']        = $data['thumb'];
        } else {
            $goods_data['thumb']        = $data['images'][0];
        }
        $goods_data['category']      = $data['category'];
        $goods_data['category_name']    = $category->idToName($data['category']);
        $goods_data['brand']         = $data['brand'];
        $goods_data['brand_name']       = $brand->idToName($data['brand']);
        $goods_data['price']            = (int) ($data['price'] * 100);
        $goods_data['stock']            = $data['stock'];
        $goods_data['images']           = $data['images'];
        $goods_data['pinyin']           = Functions::pinyin($data['title']);
        // 开启事物
        $goods->startTrans();
        $goods_result   = (bool) $goods
            ->save($goods_data,['id' => $goods_id]);
        // 组装附表数据
        $attach_data                = [];
        $attach_data['goods_id']    = $goods_id;
        $attach_data['article']     = $data['article'];
        $attach_data['parameter']   = $data['parameter'];
        $attach_result              = (bool) $attach
            ->save($attach_data, ['goods_id' => $goods_id]);
        // 组装属性表
        $attribute_data             = [];
        foreach ($data['attribute'] as $item) {
            array_push($attribute_data, [
                'goods_id'          => $goods_id,
                'id'      => $item['id'],
                'name'    => $item['name'],
                'attach'  => $item['attach']
            ]);
        }
        // 在添加之前先删除之前的数据
        $attribute_delete_result = $attribute
            ->where('goods_id', $goods_id)
            ->delete();
        if ($attribute_delete_result !== false) {
            $attribute_delete_result = true;
        }

        // TODO saveAll方法新增数据返回的是包含新增模型（带自增ID）的数据集对象  因此这个地方的bool值需要通过其他方式获取
        $attribute_result = true;
        if (count($attribute_data) > 0) {
            $attribute_result =
                (bool) $attribute
                    ->saveAll($attribute_data);
        }
        $attribute_attach_data = [];
        foreach ($data['attribute_attach'] as $item) {
            $_data                              = [];
            $_data['goods_id']  = $goods_id;
            $_data['price']     = (int) ($item['price'] * 100);
            $_data['stock']     = $item['stock'];
            $_data['thumb']     = $item['thumb'];
            $_data['attach'] = $item['attach'];
            // 计算商品编号
            $number = $goods_id;
            foreach ($item['attach'] as $_attach) {
                $number .= $_attach['id'];
            }
            $number = Functions::str_sort($number);
            $_data['thumb']     = $item['thumb'];
            $_data['number']    = $number;
            array_push($attribute_attach_data, $_data);
        }
        // TODO saveAll方法新增数据返回的是包含新增模型（带自增ID）的数据集对象  因此这个地方的bool值需要通过其他方式获取
        $attribute_attach_delete_result =
            $attribute_attach
                ->where('goods_id', $goods_id)
                ->delete();
        if ($attribute_attach_delete_result !== false) {
            $attribute_attach_delete_result = true;
        }

        $attribute_attach_result = true;
        if (count($attribute_attach_data) > 0) {
            $attribute_attach_result =
                (bool) $attribute_attach
                    ->saveAll($attribute_attach_data);
        }
        if ($goods_result &&
            $attach_result &&
            $attribute_result &&
            $attribute_delete_result &&
            $attribute_attach_delete_result &&
            $attribute_attach_result) {
            $goods->commit();
            return Functions::result(STATUS_CODE::SUCCESS, '更新成功');
        }
        $goods->rollback();
        return Functions::result(STATUS_CODE::CREATE_FAIL, '更新失败!');
    }

    /**
     * @purpose 通过ID更新商品状态
     * @param int $goods_id
     * @param int $status
     * @return array
     */
    public static function status (int $goods_id, int $status):array
    {
        if (!in_array($status, [1,2,3,4,99])) {
            return Functions::result(
                STATUS_CODE::PARAMETER_ERROR,
                '不存在的状态值!'
            );
        }
        $model = new \app\model\Goods();
        if ($model->updateStatusById($goods_id, $status)) {
            return Functions::result(
                STATUS_CODE::SUCCESS,
                '操作成功!'
            );
        }

        return Functions::result(
            STATUS_CODE::UPDATE_FAIL,
            '操作失败!'
        );
    }
}